import React from 'react';
import moment from 'moment';
import _ from 'underscore';
import { Scope } from 'lib/scopeFactory';
import ApiFactory from 'lib/ApiFactory';
import format from 'lib/util/format';
import {coreApi, corePutApi} from '../apis/core-util';

let defaultPostApi = ApiFactory({
  url: params => BlueWare.urlPrefix + '/app/' + params.appId + '/' + params.urlName + '.json',
  method: 'post'
});

export default class AlertScope extends Scope {
  constructor(props) {
    super(props);

    this.$state = {
      appName: '',
      alarmName: '',
      alarmType: 1,
      isMuted: 0, //是否禁用，1 禁用，0启用
      cpm: 10,
      rule: []
    }; // $state

    this.options = [
      {
        label: '响应时间',
        value: '1',
        ruleType: 1,
        cpm: 10,
        groupBy: 1,
        createable: true,
        // criteria: CRITERIA,
        criteria: [{
            'severity': 2, //策略定义级别 1、报警 ALERT 2、告警 WARN
            'criteriaType': 1, //类型 1、数值 2、频率 3、无事件
            'duration': 5, //持续时间 单位：分钟
            'operation': 'gt', //运算符 gt >
            'thresholdMin': 1000, //阈值 单位：毫秒 或 百分比
            'threshold': 1000 //阈值 单位：毫秒 或 百分比
          },{
            'severity': 1,
            'criteriaType': 1,
            'duration': 5,
            'operation': 'gt',
            'thresholdMin': 1000,
            'threshold': 2000
          }]
      },
      {
        label: '崩溃率',
        value: '2',
        ruleType: 2,
        cpm: 10,
        groupBy: 1,
        createable: true,
        // criteria: CRITERIA,
        criteria: [{
            'severity': 2,
            'criteriaType': 2,
            'duration': 5,
            'operation': 'gt',
            'thresholdMin': 0.05, //阈值 单位：毫秒 或 百分比
            'threshold': 0.2
          },{
            'severity': 1,
            'criteriaType': 2,
            'duration': 5,
            'operation': 'gt',
            'thresholdMin': 0.05,
            'threshold': 1
          }]
      },
      {
        label: 'http错误率',
        value: '3',
        ruleType: 3,
        cpm: 10,
        groupBy: 1,
        createable: true,
        // criteria: CRITERIA,
        criteria: [{
            'severity': 2,
            'criteriaType': 2,
            'duration': 5,
            'operation': 'gt',
            'thresholdMin': 1, //阈值 单位：毫秒 或 百分比
            'threshold': 3
          },{
            'severity': 1,
            'criteriaType': 2,
            'duration': 5,
            'operation': 'gt',
            'thresholdMin': 1,
            'threshold': 5
          }]
      },
      {
        label: '网络错误率',
        value: '4',
        ruleType: 4,
        cpm: 10,
        groupBy: 1,
        createable: true,
        // criteria: CRITERIA,
        criteria: [{
            'severity': 2,
            'criteriaType': 2,
            'duration': 5,
            'operation': 'gt',
            'thresholdMin': 1, //阈值 单位：毫秒 或 百分比
            'threshold': 3
          },{
            'severity': 1,
            'criteriaType': 2,
            'duration': 5,
            'operation': 'gt',
            'thresholdMin': 1,
            'threshold': 5
          }]
      }
    ]; // options

    if (props.isNew === true) {
      let defaultSelectedIndex = 0;

      this.options[defaultSelectedIndex].createable = false;
      this.$state.rule.push(this.options[defaultSelectedIndex]);
    }

    this.policyCreateApi = defaultPostApi({
      appId: BlueWare.appId,
      urlName: 'createAlarmStrategy'
    });

    this.policyUpdateApi = corePutApi({
      appId: BlueWare.appId,
      urlName: 'updateAlarmStrategy'
    });
  }

  $add_type(payload) {
    // debugger
    let index = _.findIndex(this.options, (item) => {
      return item.createable === true;
    });

    if (index !== -1) {
      let policy = this.options[index];

      this.options = [
        ...this.options.slice(0, index),
        _.extend({}, policy, {
          createable: false
        }),
        ...this.options.slice(index + 1)
      ];

      this.$state.rule.push(policy);
      this.emit();
      // console.log( this.options );
    }
  } // $add_type

  $change_value({key, value}) {
    this.$state[key] = value;
    this.emit();
  }

  $change_rule_value({index, key, value}) {
    let policy = this.$state.rule[index];

    if (key === 'operation') {
      policy.criteria.forEach(criteria => {
        criteria.operation = value;
      });
      return false;
    }

    if (_.has(policy, key)) {
      if (key === 'ruleType') {
        let optionIndex = _.findIndex(this.options, (option) => {
          return option.value === '' + policy.ruleType;
        });

        if (optionIndex !== -1) {
          this.options[optionIndex].createable = true;

          let nextIndex = _.findIndex(this.options, (option) => {
            return option.value === value;
          });

          policy = this.options[nextIndex];
          this.options[nextIndex].createable = false;
        }
      } else {
        policy[key] = value;
      }

      this.$state.rule[index] = policy;
      this.emit();
    }
  } // $change_rule_value

  $change_criteral_value({index, position, key, value}) {
    let policy = this.$state.rule[index];

    // Check object is exists.
    if (_.isObject(policy)) {
      let criteria = _.find(policy.criteria, (item, index) => {
        return index === position;
      });

      if (_.has(criteria, key)) {
        // Update value.
        criteria = Object.assign({}, criteria, {
          [key]: value
        });

        policy = Object.assign({}, policy, {
          criteria: [
            ...policy.criteria.slice(0, position),
            criteria,
            ...policy.criteria.slice(position + 1)
          ]
        });

        this.$state.rule = [
          ...this.$state.rule.slice(0, index),
          policy,
          ...this.$state.rule.slice(index + 1)
        ];

        this.emit();
      }
    }
  } // $change_criteral_value

  $remove_type({index, label}) {
    let { rule } = this.$state;
    this.$state.rule = [
      ...this.$state.rule.slice(0, index),
      ...this.$state.rule.slice(index + 1)
    ];

    index = _.findIndex(this.options, (item) => {
      return item.label === label;
    });

    if (index !== -1) {
      let policy = this.options[index];

      this.options = [
        ...this.options.slice(0, index),
        Object.assign({}, policy, {
          createable: true
        }),
        ...this.options.slice(index + 1)
      ];
    }

    // console.log( this.options );
    this.emit();
  } // $remove_type

  $submit_policy() {
    if (this.viewInstance.props.isNew === false) {
      this.policyUpdateApi.post(p => {
        p.data = JSON.stringify(this.$state);
        p.contentType = 'application/json';

        return p;
      }).then((res) => {
        // console.log('policyUpdateApi');
        this.viewInstance.close();
        this.viewInstance.props.onCompleted();
      })
    }
    else {
      this.policyCreateApi.fetch(p => {
        p.data = JSON.stringify(this.$state);
        p.contentType = 'application/json';

        return p;
      }).then((res) => {
        // debugger
        // console.log('policyCreateApi');
        this.viewInstance.close();
        this.viewInstance.props.onCompleted();
        if (res.status === 0) {
          // this.instanseView.props.history.pushState(null, '/');
        }
      });
    }
  } // $submit_policy

  fetch() {
    let { appId, alarmName } = this.viewInstance.props;
    coreApi({
      urlName:'queryAlarmStrategy',
      appId,
      alarmName
    }).fetch().then((policy) => {
      // debugger
      if (_.has(policy, 'appId')) {
        this.$state = _.extend({}, this.$state, policy, {
          originalAlarmName: policy.alarmName
        });

        this.$state.rule.forEach((rule, index) => {
          let item = _.find(this.options, (option) => {
            return option.ruleType === rule.ruleType;
          });

          if (!_.isEmpty(item)) {
            item.createable = false;
          }
        });
      }
    }).fail(() =>{

    }).always(() => {
      this.state.loading = false;
      this.emit();
    });
  }

  $load() {
    if (this.viewInstance.props.isNew === false) {
      this.fetch();
    }
  }
}
